package com.example.spgl.service.impl;
import com.example.spgl.service.FileService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
public class FileServiceImpl implements FileService {
    /**
     * 文件返回域名(请求下载的接口)
     *
     */
    private static final String DOMAIN = "http://localhost:8090/file/download/";
    /**
     * 文件的物理存储位置
     */
    private static final String STORE_DIR = "E:\\文件下载\\";

    /**
     * 上传图片，返回url
     *
     * @param file
     * @param fileName
     * @return
     * @throws IOException
     */
    @Override
    public String uploadFile(MultipartFile file, String fileName) throws IOException {
        //获取文件流
        InputStream is = file.getInputStream();
        //在服务器中储存文件
        FileUtils.copyInputStreamToFile(is,new File(STORE_DIR+fileName));
        //返回图片url
        String url = DOMAIN+fileName;
        System.out.println("文件url:"+url);
        return url;

    }

    /**
     * 下载图片
     * @param fileName
     * @param request
     * @param response
     */
    @Override
    public void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response){
        //获取真是的文件路径
        String filePath = STORE_DIR+fileName;
        System.out.println("+++完整路径为："+filePath);

        //下载文件
        try{
            //下载文件
            //设置响应头
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename="+fileName);
            //读取文件并写入输出流
            Files.copy(Paths.get(filePath),response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            response.setStatus(404);
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除图片
     * @param FileName
     * @return
     */
    @Override
    public boolean deleteFile(String FileName) {
        //获取文件的真实路径
        String filePath = STORE_DIR+FileName;
        System.out.println("++++完整路径为: "+filePath);

        File file = new File(filePath);
        return file.delete();
    }
}
